package com.heng.apphook

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.heng.mapbundle2.MockLocationV2

/**
 * @Author    : zhangheng227
 * date       : 2025/5/23
 */
class BusinessActivity : AppCompatActivity() {

    private var tv_longitude: TextView? = null
    private var tv_latitude: TextView? = null
    private var btn_to_setting: Button? = null

    companion object {
        private const val TAG = "BusinessActivity"
        private var isHooked = false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        try {
            setContentView(R.layout.activity_mock_bus)

            // 初始化MockLocationV2
//            MockLocationV2.init(this)
            initView()
            
            // 立即初始化数据，看看默认值
            initData()
            
            // 再延迟获取一次，确保Hook生效
            Handler(Looper.getMainLooper()).postDelayed({
                Log.d(TAG, "Refreshing data after delay...")
                initData()
            }, 1000)

        } catch (e: Exception) {
           e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        // 从设置页面返回时刷新数据
        if (tv_longitude != null && tv_latitude != null) {
            Log.d(TAG, "onResume: refreshing data")
            initData()
        }
    }

    private fun initView(){
        try {
            tv_longitude = findViewById(R.id.tv_longitude)
            tv_latitude = findViewById(R.id.tv_latitude)
            btn_to_setting = findViewById(R.id.btn_to_setting)
            btn_to_setting?.setOnClickListener {
                Intent(this, MockLocationActivity::class.java).also {
                    startActivity(it)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error in initView", e)
        }
    }

    private fun initData(){
        try {
            val locationV2 = MockLocationV2.getInstance()

            // 直接调用getLocation看看结果
            val location = locationV2.location

            if (location != null) {
                tv_longitude?.text = location.longitude?.toString() ?: "null"
                tv_latitude?.text = location.latitude?.toString() ?: "null"
            } else {
                Log.e(TAG, "Location is null!")
                tv_longitude?.text = "null"
                tv_latitude?.text = "null"
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error in initData", e)
            e.printStackTrace()
        }
    }

}